package com.glodon.paas.account.dao.mongo;

import com.glodon.paas.account.dao.OAuthTokenDao;
import com.glodon.paas.account.dao.domain.OAuthTokenEntity;
import com.google.code.morphia.query.Query;

public class OAuthTokenDaoMongoImpl extends MongoDBDao<OAuthTokenEntity, String> implements OAuthTokenDao {
	
	@Override
	public void ensureIndexes() {
		super.ensureIndexes();
		mongoDataStore.ensureIndex(this.entityClazz, "consumerKey, oAuthAuthorizationId");
	}
	
	@Override
	public OAuthTokenEntity readToken(String tokenValue) {
		Query<OAuthTokenEntity> q = this.createQuery().filter("value =", tokenValue);
		return q.get();
	}

	@Override
	public void saveToken(OAuthTokenEntity token) {
		super.update(this.createQuery().filter("value =", token.getValue()), token);
	}

	@Override
	public OAuthTokenEntity removeToken(String tokenValue) {
		Query<OAuthTokenEntity> q = this.createQuery().filter("value =", tokenValue);
		return mongoDataStore.findAndDelete(q);
	}
	
	@Override
	public void removeToken(String consumerKey, String authorizerId) {
		Query<OAuthTokenEntity> q = this.createQuery().filter("consumerKey = ", consumerKey)
												.filter("oAuthAuthorizationId = ", authorizerId);
		this.deleteByQuery(q);
	}

}
